package com.elive.controller.backend;


import com.elive.common.ServerResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("upload")
public class FileUploadControllerx {

    public static final String ROOT = "/Users/wuyin/Desktop/project/eliveImage";

    private final ResourceLoader resourceLoader;

    @Autowired
    public FileUploadControllerx(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }


    @RequestMapping(method = RequestMethod.POST, value = "/up.do")
    public Object handleFileUpload(@RequestParam("file") MultipartFile file,
                                   RedirectAttributes redirectAttributes, HttpServletRequest request) throws IOException {


        if (!file.isEmpty()) {
            String fileName = file.getOriginalFilename();
            //获取扩展名
            String fileExtensionName = fileName.substring(fileName.lastIndexOf(".")+1);
            //文件上传上去的名字
            String uploadFileName = UUID.randomUUID().toString()+"."+fileExtensionName;
            Files.copy(file.getInputStream(),  Paths.get(ROOT, uploadFileName));
            String url = uploadFileName;
            return ServerResponse.createBySuccess("成功", url);
        }
        return ServerResponse.createByErrorMessage("你上传的文件为空");
    }
}
